package com.house365.core.util.db;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.house365.core.util.db.DataBaseOpenHelper.DataBaseOpenListener;
/**
 *@author py
 *@date 2012-9-19
 *@comment
 */
public class DataBaseService{
	
		private DataBaseOpenHelper dbOpenHelper;

		// private Context context;
		public DataBaseService() {
			
		}
		public DataBaseService(Context context,String dbname,int version,DataBaseOpenListener listener) {
			// this.context = context;
			dbOpenHelper = new DataBaseOpenHelper(context,dbname,version,listener );
		}

//		public void save(String sql,Object[] values) {
//			SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
//			database.execSQL(sql,values);
//			// database.close();可以不关闭数据库，他里面会缓存一个数据库对象，如果以后还要用就直接用这个缓存的数据库对象。但通过
//			// context.openOrCreateDatabase(arg0, arg1, arg2)打开的数据库必须得关闭
//
//		}

		public void execute(String sql,Object[] values) {
			SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
			database.execSQL(
					sql,
					values);
		}

		public Object query(String sql,String[] values,DBQuery dbQuery) {
			SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
			Cursor cursor = database.rawQuery(sql,values);
			Object o = dbQuery.onQueryResult(cursor);
			cursor.close();
			return o;
			
		}


		public long getCount(String sql) {
			SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
			Cursor cursor = database.rawQuery(sql, null);
			if (cursor.moveToNext()) {
				return cursor.getLong(0);
			}
			return 0;
		}
		public interface DBQuery{
			public Object onQueryResult(Cursor cursor);
		}
		public DataBaseOpenHelper getDbOpenHelper() {
			return dbOpenHelper;
		}
		public void destory(){
			dbOpenHelper.close();
		}
	}
